import React, { useState, useEffect, useRef } from "react";
import { Upload, Button, Card, Space, message, Spin, Table, Image } from "antd";
import { UploadOutlined, SearchOutlined } from "@ant-design/icons";
import Icon from "@/components/Icon";
import * as faceapi from "face-api.js";

const FaceRecognition = () => {
  const [imageUrl, setImageUrl] = useState(null);
  const [loading, setLoading] = useState(false);
  const [detections, setDetections] = useState([]);
  const [currentImage, setCurrentImage] = useState(null);
  const [modelsLoaded, setModelsLoaded] = useState(false);
  const [faceImages, setFaceImages] = useState([]);
  const imageRef = useRef(null);

  // 加载 face-api 模型
  useEffect(() => {
    const loadModels = async () => {
      try {
        setLoading(true);
        await Promise.all([
          faceapi.nets.ssdMobilenetv1.loadFromUri("/models"),
          faceapi.nets.faceLandmark68Net.loadFromUri("/models"),
          faceapi.nets.faceExpressionNet.loadFromUri("/models"),
          faceapi.nets.ageGenderNet.loadFromUri("/models"),
        ]);
        setModelsLoaded(true);
        message.success("模型加载完成");
      } catch (error) {
        console.log(error);
        message.error("模型加载失败");
      } finally {
        setLoading(false);
      }
    };
    loadModels();
  }, []);

  // 人脸检测
  const handleFaceDetection = async () => {
    if (!modelsLoaded) {
      message.warning("模型尚未加载完成，请稍候");
      return;
    }

    if (!currentImage || !imageRef.current) {
      message.warning("请先上传图片");
      return;
    }

    const img = imageRef.current;

    // 确保图片完全加载
    if (!img.complete) {
      img.onload = () => handleFaceDetection();
      return;
    }

    try {
      setLoading(true);

      // 检测人脸
      const detectedFaces = await faceapi
        .detectAllFaces(img)
        .withFaceLandmarks()
        .withFaceExpressions()
        .withAgeAndGender();

      if (!detectedFaces || detectedFaces.length === 0) {
        message.warning("未检测到人脸");
        setDetections([]);
        setFaceImages([]);
        return;
      }

      setDetections(detectedFaces);

      // 提取每个人脸信息
      const faceData = await Promise.all(
        detectedFaces.map(async (detection, index) => {
          const box = detection.detection.box;
          const tempCanvas = document.createElement("canvas");
          const tempCtx = tempCanvas.getContext("2d");

          tempCanvas.width = box.width;
          tempCanvas.height = box.height;

          tempCtx.drawImage(
            img,
            box.x,
            box.y,
            box.width,
            box.height,
            0,
            0,
            box.width,
            box.height
          );

          // 获取主要表情
          const expressions = detection.expressions;
          const mainExpression = Object.entries(expressions).reduce((a, b) =>
            a[1] > b[1] ? a : b
          )[0];

          return {
            id: index + 1,
            image: tempCanvas.toDataURL(),
            age: Math.round(detection.age),
            gender: detection.gender,
            expression: mainExpression,
            confidence: Math.round(detection.detection.score * 100),
          };
        })
      );

      setFaceImages(faceData);
    } catch (error) {
      console.error(error);
      message.error("人脸检测失败");
    } finally {
      setLoading(false);
    }
  };

  // 处理上传
  const handleImageUpload = (file) => {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      message.error("只能上传图片文件！");
      return false;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      setImageUrl(e.target.result);
      setCurrentImage(file);
      setDetections([]);
      setFaceImages([]);
    };
    reader.readAsDataURL(file);
    return false;
  };

  const props = {
    name: "file",
    multiple: false,
    accept: "image/*",
    showUploadList: false,
    beforeUpload: handleImageUpload,
  };

  const handleReset = () => {
    setImageUrl(null);
    setCurrentImage(null);
    setDetections([]);
    setFaceImages([]);
  };

  return (
    <>
      <Spin spinning={loading}>
        <div className="flex flex-col md:flex-row gap-8">
          {/* 左侧上传区域 */}
          <div className="flex-1">
            <Card title="上传图片" className="h-full">
              <div className="h-[300px] w-full relative overflow-hidden flex items-center justify-center border-2 border-dashed border-gray-200 rounded-lg hover:border-blue-400 transition-colors duration-300">
                {imageUrl ? (
                  <img
                    ref={imageRef}
                    src={imageUrl}
                    alt="上传图片"
                    style={{
                      width: "100%",
                      height: "100%",
                    }}
                    className="rounded-lg shadow-sm"
                  />
                ) : (
                  <Icon
                    name="line-md:image-twotone"
                    size={80}
                    color="#1890ff"
                  />
                )}
              </div>
              <div className="mt-4 flex justify-center">
                <Space>
                  <Upload {...props}>
                    <Button type="primary" icon={<UploadOutlined />}>
                      上传图片
                    </Button>
                  </Upload>
                  <Button
                    type="primary"
                    icon={<SearchOutlined />}
                    onClick={handleFaceDetection}
                    disabled={!imageUrl}
                  >
                    开始识别
                  </Button>
                  <Button onClick={handleReset}>重置</Button>
                </Space>
              </div>
            </Card>
          </div>
          {/* 右侧识别结果区域 */}
          <div className="flex-1 min-w-0">
            <Card title="识别结果" className="h-full w-full">
              <div>
                <Image.PreviewGroup>
                  <Table
                    style={{ width: "100%" }}
                    tableLayout="fixed"
                    scroll={{ y: 400 }} // ✅ 确保跟随父容器
                    rowKey="id"
                    dataSource={faceImages}
                    columns={[
                      {
                        title: "头像",
                        dataIndex: "image",
                        width: 100,
                        render: (src) => (
                          <div className="cursor-pointer">
                            <Image
                              src={src}
                              width={64}
                              height={64}
                              style={{
                                objectFit: "cover",
                                borderRadius: "50%",
                              }}
                            />
                          </div>
                        ),
                      },
                      {
                        title: "性别",
                        dataIndex: "gender",
                        width: 80,
                        render: (g) => (g === "male" ? "男" : "女"),
                      },
                      {
                        title: "年龄",
                        dataIndex: "age",
                        width: 80,
                        render: (a) => `${a}岁`,
                      },
                      {
                        title: "表情",
                        dataIndex: "expression",
                        width: 120,
                      },
                      {
                        title: "置信度",
                        dataIndex: "confidence",
                        width: 120,
                        render: (c) => `${c}%`,
                      },
                    ]}
                    pagination={false}
                  />
                </Image.PreviewGroup>
              </div>
            </Card>
          </div>
        </div>
      </Spin>
    </>
  );
};

export default FaceRecognition;
